#include <stdio.h>
#include <stdlib.h>
#include "AdjListG.h"

Graph createGraph(GraphType type) {
    Graph G = malloc(sizeof(GraphS));
    if (G==NULL){
        fprintf(stderr, "Memory allocation failed for Graph.\n");
        exit(EXIT_FAILURE);
    }
    G->type=type;
    G->nodenum = 0;
    G->arcnum = 0;
    for (int i=0;i<MAX_NODE_NUM;++i)
        G->nodes[i].adjs=NULL;
    return G;
}

void freeGraph(Graph G){
    free(G);
}

void add_arc(Graph G,char h,char t,float w){
    int i,j;
    for (i=0;i<G->nodenum;++i)
        if (G->nodes[i].id==h) break;
    if (i==G->nodenum){
        G->nodes[i].id=h;
        G->nodenum++;
        }
    for (j=0;j<G->nodenum;++j)
        if (G->nodes[j].id==t) break;
    if (j==G->nodenum){
        G->nodes[j].id=t;
        G->nodenum++;
        }

    PtArc *p = &(G->nodes[i].adjs);
    while (*p != NULL) 
        p = &(*p)->next;
    *p = malloc(sizeof(Arc));
    if (*p == NULL) {
        fprintf(stderr, "Error: Memory allocation failed for new arc.\n");
        return;
    }
    (*p)->head = j;
    (*p)->weight = w;
    (*p)->next = NULL;
}

void print_Graph(Graph G){
    int i;
    for (i=0;i<G->nodenum;++i){
        printf("%c: ",G->nodes[i].id);
        Arc * arc =G->nodes[i].adjs;
        while (arc!=NULL){
            printf("->%c(%4.1f)",G->nodes[arc->head].id,arc->weight);
            arc = arc->next;
        }
        printf("\n");
    }
}

int main(){
    Graph G=createGraph(DG);
    add_arc(G,'a','b',10);
    add_arc(G,'b','c',20);
    add_arc(G,'c','a',30);
    // print_Graph(G);
    add_arc(G,'a','d',40);
    add_arc(G,'c','d',50);
    print_Graph(G);
    free(G);
    return 0;
}